import axios from 'axios'
import {
    MessageBox,
    Message
} from 'element-ui'
import {
    getAccessToken,
    getRefreshToken,
    setAccessToken
} from "./auth.js"
import {
    Refresh
} from "@/api/modules/user"
import store from "@/store"
import {
    removeAccessToken,
    removeRefreshToken
} from "@/utils/auth"
import router from "@/router"
import {
    resetRouter,
    redirectToLogin
} from "@/router"
import {
    refreshAccessToken
} from "./request/user"
import {
    RequestDealWithModuleList
} from "@/utils/tools"
// 标志变量，用于跟踪是否已经执行了刷新accessToken的操作
let isRefreshing = false;
// 需要重新发送的请求队列
let requestsQueue = [];
console.log('baseUrl', process.env)
    // 创建服务器
const service = axios.create({
        baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
        // withCredentials: true, // send cookies when cross-domain requests
        // timeout: 5000 // request timeout
    })
    // 请求拦截器
service.interceptors.request.use(
    config => {
        const accessToken = getAccessToken()
        console.log(accessToken)
            // console.log(config)
            // 如果存在accessToken并且header不存在用户验证
        if (accessToken && !config.headers.Authorization) {
            config.headers.Authorization = getAccessToken()
        }
        // do something before request is sent

        // if (store.getters.token) {
        //     // let each request carry token
        //     // ['X-Token'] is a custom headers key
        //     // please modify it according to the actual situation
        //     config.headers['token'] = getToken()
        // }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// // 响应拦截器
service.interceptors.response.use(

    // 响应处理
    response => {
        const res = response.data
            // console.log('response', res);
            // AccessToken过期处理
        if (res.status == 401) {
            const {
                data
            } = res;
            // 缺乏/篡改AccessToken或RefreshToken 
            if (data == 'unauthorized' || data == 'tampered') {
                removeAccessToken()
                removeRefreshToken()
                Message({
                    message: res.msg,
                    type: "error",
                    duration: 5 * 1000
                })
                return router.push("/login");
            }
            // AccessToken 已过期或注销
            if (!isRefreshing) {
                isRefreshing = true
                if (data == 'access') {

                    removeAccessToken();
                    let refreshToken = getRefreshToken()
                    console.log(refreshToken)
                    if (!refreshToken) router.push("/login")
                        // 刷新RefreshToken
                    Refresh(refreshToken).then(success => {
                        // 刷新accessToken成功
                        if (success.status == 200) {
                            const newAccessToken = success.data.AccessToken
                                // 设置AccessToken
                            setAccessToken(newAccessToken)
                                // 重新发送请求队列中的请求
                            requestsQueue.forEach(cb => cb(newAccessToken));
                            requestsQueue = [];
                            window.location.reload();

                            // 或者使用路由跳转到当前页面
                            router.replace(router.currentRoute);
                            return service(response.config);
                        }
                        // refreshToken失效
                        else {
                            removeAccessToken();
                            removeRefreshToken();
                            Message({
                                message: "登录已过期",
                                type: "error",
                                duration: 5 * 1000
                            });
                            return router.push("/login");
                        }
                    }).finally(() => {
                        isRefreshing = false
                    })
                } else {
                    // 当前有请求正在刷新AccessToken，将当前请求加入队列中
                    return new Promise(resolve => {
                        requestsQueue.push(token => {
                            config.headers.Authorization = token;
                            resolve(service(config));
                        });
                    });
                }
            }

        }
        if (res.status == 409) {
            Message({
                message: res.msg,
                type: 'error',
                duration: 5 * 1000
            })
        }
        if (res.status == 403) {
            Message({
                message: res.msg,
                type: 'error',
                duration: 5 * 1000
            })
            router.replace("/article")
        }
        // if (res.status === 500) {
        //     // to re-login
        //     return MessageBox.confirm('网络错误', {
        //         confirmButtonText: 'Re-Login',
        //         cancelButtonText: 'Cancel',
        //         type: 'warning'
        //     }).then(() => {})
        // }    
        if (res.status == 503 && res.data !== 'module') {
            MessageBox.confirm('服务器已过期,请联系管理员', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return router.push("/login")

            }).catch(err => {
                console.log(err);
            })
        } else if (res.data == 'module' && res.status == 503) {
            // 模块开关请求问题
            RequestDealWithModuleList()
        }
        return res
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: '网络错误',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)


export default service